package com.netty.rpc.serializer;

import com.google.gson.*;

import java.io.*;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;

public interface Serializer {
    <T> T deserialize(Class<T> clazz,byte[] bytes);
    <T> byte[] enserialize(T object);
    Gson gson = new GsonBuilder().registerTypeAdapter(Class.class, new ClassCodec()).create();
    enum Algorithm implements Serializer{
        JAVA{
            @Override
            public <T> T deserialize(Class<T> clazz, byte[] bytes) {
                // 进行转化成对象
                ObjectInputStream objectInputStream = null;
                try {
                    objectInputStream = new ObjectInputStream(new ByteArrayInputStream(bytes));
                    T obj= (T) objectInputStream.readObject();
                    return obj;
                } catch (Exception e) {
                    throw new RuntimeException("反序列化失败",e);
                }
            }


            @Override
            public <T> byte[] enserialize(T object) {
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                ObjectOutputStream objectOutputStream = null;
                try {
                    objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
                    objectOutputStream.writeObject(object);
                    byte[] content = byteArrayOutputStream.toByteArray();
                    return content;
                } catch (IOException e) {
                    throw new RuntimeException("反序列化失败",e);
                }
            }
        },
        JSON{
            @Override
            public <T> T deserialize(Class<T> clazz, byte[] bytes) {
                String json=new String(bytes,StandardCharsets.UTF_8);
                return gson.fromJson(json,clazz);
            }

            @Override
            public <T> byte[] enserialize(T object) {
                String json = gson.toJson(object);
                return json.getBytes(StandardCharsets.UTF_8);
            }
        }
    }

    class ClassCodec implements JsonSerializer<Class<?>>, JsonDeserializer<Class<?>> {
        @Override
        public JsonElement serialize(Class<?> aClass, Type type, JsonSerializationContext jsonSerializationContext) {
            return new JsonPrimitive(aClass.getName());
        }

        @Override
        public Class<?> deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
            String v=jsonElement.getAsString();
            try {
                return Class.forName(v);
            } catch (ClassNotFoundException e) {
                throw new JsonParseException(e);
            }
        }
    }
}
